<template>
  <div class="inventory">
    <Search @onSearch="handleSearch" />
    <div class="px-20 mt-10 pb-40">
      <ITable
        :list="list"
        @onAdd="handleAdd"
        @onRemove="handleRemove"
        @onAddNum="handleAddNum"
        @onDelNum="handleDelNum"
        @onUpdateNum="handleUpdateNum"
        @onBlurPrice="handleBlurNum"
      />
    </div>
    <div
      class="flex items-center justify-between mx-8 p-5 bg-[#eeecec] bottom-5 left-0 right-0 absolute"
    >
      <div class="flex">
        <div>总商品数量: {{ total }}</div>
        <div class="ml-10">总入库数量: {{ totalNum }}</div>
        <div class="ml-10">总金额: {{ totalPrice }}</div>
      </div>
      <div>
        <el-button type="primary" @click="handleSave">确认入库</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Search from "./components/Search.vue";
import ITable from "./components/Table.vue";
import rfdc from "rfdc";
import { mockList } from "./constants";

export default {
  name: "HomePage",
  components: {
    Search,
    ITable,
  },

  data() {
    return {
      list: mockList(),
    };
  },

  computed: {
    total() {
      // 过滤掉相同code
      return this.list.filter((item, index, arr) => {
        return arr.findIndex((item2) => item2.code === item.code) === index;
      }).length;
    },
    totalNum() {
      return this.list.reduce((total, item) => {
        return total + item.inventoryNum;
      }, 0);
    },
    totalPrice() {
      return this.list.reduce((total, item) => {
        return total + item.unitPrice * item.inventoryNum;
      }, 0);
    },
  },

  methods: {
    handleSearch(val) {
      const data = mockList();
      const newList = val
        ? data.filter((item) => {
            return item.name.includes(val) || item.code.includes(val);
          })
        : mockList();
      this.list = newList;
    },
    handleAdd(index) {
      const data = rfdc()(this.list);
      //判断是不是相同的code只有一条数据
      if (!this.list[index].add) {
        data[index].add = true;
        this.list = data;
        return;
      }

      // 下标位置插入一条一样的数据
      data.splice(index + 1, 0, {...data[index], id: Math.random()});
      this.list = data;
    },

    handleRemove(index) {
      const data = rfdc()(this.list);
      // data[index] = {
      //   ...data[index],
      //   add: false,
      //   inventoryNum: 0,
      //   recommend: [
      //     {
      //       recommendNum: 0,
      //       location: [],
      //     },
      //   ],
      //   unitPrice: 0,
      //   remark: "",
      // };
      //删除这条数据
      data.splice(index, 1);
      this.list = data;
    },

    handleAddNum(index) {
      const data = rfdc()(this.list);
      data[index].recommend.push({
        location: [],
        recommendNum: 0,
      });
      this.list = data;
    },

    handleDelNum(index, _, colIndex) {
      const data = rfdc()(this.list);
      data[index].recommend.splice(colIndex, 1);
      this.list = data;
    },

    // 输入库存单价之后计算平均价
    handleBlurNum(_, index, row) {
      const price = this.calcPrice(row);
      const data = rfdc()(this.list);
      data[index].averagePrice = price;
      this.list = data;
    },
    /**
     * 计算平均价格
     * （库存价*库存数量）+（入库单价*入库数量）/（库存数量+入库数量）
     */
    calcPrice(row) {
      const {
        inventoryPrice, // 库存单价
        inventoryNum, //入库数量
        storeNum, //库存数量
        unitPrice, //入库单价
      } = row;
      const avgPrice =
        (inventoryPrice * storeNum + unitPrice * inventoryNum) /
        (storeNum + inventoryNum);
      return avgPrice.toFixed(2) ?? 0;
    },

    handleUpdateNum(_, index, __, nodeIndex) {
      const data = rfdc()(this.list);
      data[index].recommend[nodeIndex].recommendNum = 0;
      this.list = data;
    },

    handleSave() {
      if (!this.totalNum || !this.totalPrice) {
        this.$message.warning("请填写入库商品信息");
        return;
      }
      this.$message.success("入库成功");
    },
  },
};
</script>

<style>
.inventory {
  position: relative;
  min-height: 100vh;
}
</style>
